<?php

namespace Modules\Shop\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Shop\Entities\Category;
use Modules\Shop\Http\Requests\CategoryRequest;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
    	$categorys = Category::getTreeCategory();
        return view('shop::category.index',compact ('categorys'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        return view('shop::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
    	Category::create ($request->all ());
    	session ()->flash ('success','分类添加成功');
    	return back ();
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('shop::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit($id)
    {
    	$category= Category::find($id);
    	$categorys = Category::getTreeCategory ($category);
        return view('shop::category.edit',compact ('categorys','category'));
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(CategoryRequest $request,$id)
    {
    	$category = Category::find($id);
    	$post = $request->all ();
    	$category->cname = $post['cname'];
    	$category->pid = $post['pid'];
    	$category->save();
    	session ()->flash ('success','分类编辑成功');
    	return redirect ()->route ('category.index');
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
    	$category = Category::find($id);
    	if (Category::hasChildCategory($category)){
			session ()->flash ('danger','请删除当前分类的子分类，再来删除该分类');
			return back ();
		}
		Category::destroy ($id);
    	session ()->flash ('success','分类删除成功');
    	return back ();
    }
}
